package org.ithasu.filpilote.data.entities;

import java.util.ArrayList;
import java.util.List;

import org.ithasu.tools.TimeTools;
import org.ithasu.tools.data.EList;
import org.ithasu.tools.net.JSONTools;
import org.ithasu.tools.net.JSONTools.JSONContext;
import org.ithasu.tools.net.JSONTools.JSONEntity;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class Rule implements JSONEntity {

	private final static String JSON_PROPERTY_DAYS = "days";
	private final static String JSON_PROPERTY_TIME = "time";
	private final static String JSON_PROPERTY_ZONES = "zones";
	private final static String JSON_PROPERTY_MODE = "mode";

	private final EList<Zone> zones = new EList<Zone>(null);
	/** Use Calendar.SUNDAY to calendar.SATURDAY */
	private final ArrayList<Integer> days = new ArrayList<Integer>();
	private Mode newMode;
	private long minutesFromMidnight;

	public Rule(JSONContext context, JSONObject object) {
		parseJSON(context, object);
	}

	// -- Properties ----------------------------------------

	public EList<Zone> getZones() {
		return zones;
	}

	public ArrayList<Integer> getDays() {
		return days;
	}

	public Mode getNewMode() {
		return newMode;
	}

	public long getMinutesFromMidnight() {
		return minutesFromMidnight;
	}

	// -- String ----------------------------------------

	@Override
	public String toString() {
		String days = null;
		for (Integer day : this.days) {
			if (days == null) {
				days = TimeTools.day(day);
			} else {
				days += ", " + TimeTools.day(day);
			}
		}
		return "[" + days + "] " + TimeTools.minutes(minutesFromMidnight) + " -> " + zones + " = " + newMode.name();
	}

	// -- JSON ----------------------------------------

	@SuppressWarnings("unchecked")
	@Override
	public JSONObject toJSON(JSONContext context) {
		JSONObject o = new JSONObject();
		o.put(JSON_PROPERTY_ZONES, zones.toJSON(context));
		o.put(JSON_PROPERTY_DAYS, days);
		o.put(JSON_PROPERTY_TIME, minutesFromMidnight);
		o.put(JSON_PROPERTY_MODE, newMode.name());
		return o;
	}

	@Override
	public void parseJSON(JSONContext context, JSONObject o) {
		this.zones.parseJSON(context, JSONTools.getProperty(JSONObject.class, o, JSON_PROPERTY_ZONES));
		this.days.clear();
		List<?> dl = JSONTools.getProperty(JSONArray.class, o, JSON_PROPERTY_DAYS);
		if (dl != null) {
			for (Object d : dl) {
				long l = JSONTools.safeCast(Long.class, d);
				days.add((int) l);
			}
		}
		this.minutesFromMidnight = JSONTools.getProperty(Long.class, o, JSON_PROPERTY_TIME);
		this.newMode = Mode.valueOf(JSONTools.getProperty(String.class, o, JSON_PROPERTY_MODE, Mode.COMFORT.name()));
	}
}
